package com.lancoo.znbkxx.teacher.adapter

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.os.Build
import android.view.View
import android.webkit.JavascriptInterface
import android.webkit.WebView
import android.webkit.WebViewClient
import android.widget.LinearLayout
import androidx.lifecycle.Lifecycle
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.BaseViewHolder
import com.lancoo.znbkxx.teacher.R
import com.lancoo.znbkxx.teacher.aibkTestCoach.auidoPlayer.SubChildVoicePlayer
import com.lancoo.znbkxx.teacher.model.data.Child
import com.lancoo.znbkxx.teacher.utils.HtmlUtils
import com.lancoo.znbkxx.teacher.utils.WebStyleUtils
import com.lancoo.znbkxx.teacher.widget.voicePlayer.VoicePlayer
import kotlinx.android.synthetic.main.item_question.view.*
import java.util.*

/**
 * @author : Admin
 * @date   : 2019/9/2 17:06
 * @desc   :
 */
class QuestionAdapter(val allCount: Int, val type: String?, val genre: Int?, layoutResId: Int,
        data: MutableList<Child>?, val lifecycle: Lifecycle,
        val player: VoicePlayer?) :
        BaseQuickAdapter<Child, BaseViewHolder>(layoutResId, data) {
    val list = mutableListOf<SubChildVoicePlayer>()

    @SuppressLint("SetTextI18n")
    override fun convert(helper: BaseViewHolder, item: Child?) {
        val position = helper.layoutPosition
        var subPlayer: SubChildVoicePlayer? = null
        with(helper.itemView) {
            if (type == "f" || type == "b" || type == "d" || (type == "N" && genre != 20) || type == "S" || type == "x" || type == "A" || type == "U" || genre == 39 || genre == 38 || genre == 40 || genre == 41) {
                tv_body.visibility = View.GONE
                wv_body.visibility = View.GONE
            } else if (type == "m") {
                tv_body.visibility = View.VISIBLE
                wv_body.visibility = View.GONE
                tv_body.text = "${position + 1}."
            } else if (type == "H") {
                tv_body.visibility = View.VISIBLE
                wv_body.visibility = View.GONE
                if (item!!.ChildSectionName.isNotEmpty()) {
                    tv_body.text = HtmlUtils.setText(
                            "${item.ChildSectionName} ${item.ChildDisplay}\n${position + 1}.${item.ChildAsk}")
                } else {
                    tv_body.text = HtmlUtils.setText("${position + 1}.${item.ChildAsk}")
                }
            } else {
                if (item!!.ChildAsk.contains("<")) {
                    if (type == "Q" || type == "k") {
                        wv_body.visibility = View.VISIBLE
                        tv_body.visibility = View.GONE
                        wv_body.addJavascriptInterface(MyJavaScript(mContext, wv_body), "APP");
                        wv_body.webViewClient = object : WebViewClient() {

                            override fun onPageFinished(view: WebView?, url: String?) {
                                super.onPageFinished(view, url)
                                if (Build.BRAND.toLowerCase(Locale.ROOT).contains("oppo")) {
                                    wv_body.loadUrl(
                                            "javascript:window.APP.resize(document.body.getBoundingClientRect().height)");
                                }
                            }
                        }
                        WebStyleUtils.showWebViewCssStyle(
                                context,
                                wv_body,
                                if (data.size > 0) "${
                                helper.layoutPosition
                                }.${
                                item.ChildAsk
                                }" else item.ChildAsk,
                                !WebStyleUtils.hasTable(item.ChildAsk)
                        )
                    } else {
                        wv_body.visibility = View.GONE
                        tv_body.visibility = View.VISIBLE
                        if (data.size > 1) {
                            tv_body.text = HtmlUtils.setText("${position + 1}.${item.ChildAsk}")
                        } else {
                            tv_body.text = HtmlUtils.setText(item.ChildAsk)
                        }
                    }
                } else {
                    wv_body.visibility = View.GONE
                    val path = item.ChildAudio.Path
                    if (path.isNotEmpty()) {
                        ll_player.visibility = View.VISIBLE
                        tv_body.text = "${position + 1}."
                        helper.addOnClickListener(R.id.iv_subchildAudioIcon)
                        subPlayer = SubChildVoicePlayer(
                                context,
                                sb_subchildMusicProgress,
                                path,
                                iv_subchildAudioIcon,
                                false,
                                object : SubChildVoicePlayer.PlayListener {
                                    override fun initFirstPlay() {
                                        player?.pause()
                                    }

                                    override fun onFinishPlay() {
                                        subPlayer?.rePlay()
                                    }

                                    override fun onStartPlay() {
                                        for (i in list.indices) {
                                            if (i != position) {
                                                list[i].pause()
                                            }
                                        }
                                        subPlayer?.play()
                                        player?.pause()
                                    }
                                })
                        list.add(subPlayer!!)
                        lifecycle.addObserver(subPlayer!!)
                    } else {
                        ll_player.visibility = View.GONE
                    }
                    if (data.size > 1) {
                        tv_body.visibility = View.VISIBLE
                        tv_body.text = HtmlUtils.setText("${position + 1}.${item.ChildAsk}")
                    } else {
                        if (item.ChildAsk.isNotEmpty()) {
                            tv_body.text = HtmlUtils.setText(item.ChildAsk)
                        } else {
                            tv_body.visibility = View.GONE
                        }
                    }
                }
            }
            val answer =
                    if (type == "m") item!!.ItemList[position].ItemAnswer else item!!.ItemList[0].ItemAnswer
//            if (type != "m") {
            val optionListBean = item.ChildOptionList
            if (optionListBean.isNotEmpty()) {
                rv.visibility = View.VISIBLE
                optionListBean.forEach {
                    it.isAnswer = it.OptionIndex == answer
                }
                val adapter =
                        ChoiceAdapter(allCount, type, R.layout.item_question_choice, optionListBean)
                val manager = LinearLayoutManager(context)
                manager.orientation = RecyclerView.VERTICAL
                rv.layoutManager = manager
                rv.adapter = adapter
            } else {
                rv.visibility = View.GONE
            }
//            } else {
//                val stuOptionList = item.StuOptionList[helper.layoutPosition]
//                rv.visibility = View.VISIBLE
//                stuOptionList.forEach {
//                    it.isAnswer = it.Option == answer
//                }
//                val adapter =
//                    ChoiceAdapter(allCount, type, R.layout.item_question_choice, stuOptionList)
//                val manager = LinearLayoutManager(context)
//                manager.orientation = RecyclerView.VERTICAL
//                rv.layoutManager = manager
//                rv.adapter = adapter
//            }
        }
    }

    fun getSubPlayer(): MutableList<SubChildVoicePlayer> {
        return list
    }

    inner class MyJavaScript(val context: Context, private val webView: WebView) : Activity() {
        @JavascriptInterface
        fun resize(height: Float) {
            runOnUiThread {
                val layoutParams = LinearLayout.LayoutParams(
                        context.resources.displayMetrics.widthPixels - (20 * mContext.resources.displayMetrics.density).toInt(),
                        ((height + 100) * mContext.resources.displayMetrics.density).toInt()
                )
                webView.layoutParams = layoutParams
            }
        }
    }
}